<?php
require_once '../../include.php';

$tx = $_GET['tx'];
$at_token = 'hkd5dqClgg1vf7zZtNL9nfOJ5Tdcf-xpzkCanRkZFPXiCncJslXJ1UTBEbG'; //your_pdt_identity_token
$item_number=$_GET['item_number'];
$payment_stauts=$_GET['st'];
if($payment_stauts!=='Completed'){
	echo "Pay fail";
	die();
}
// Init cURL
$request = curl_init();
// Set request options
curl_setopt_array($request, array(
	CURLOPT_URL => 'https://www.sandbox.paypal.com/cgi-bin/webscr',//测试
	// CURLOPT_URL => 'https://www.paypal.com/cgi-bin/webscr',//正式
	CURLOPT_POST => TRUE,
	CURLOPT_POSTFIELDS => http_build_query(array(
		'cmd' => '_notify-synch',
		'tx' => $tx,
		'at' => $at_token,
		)),
	CURLOPT_RETURNTRANSFER => TRUE,
	CURLOPT_HEADER => FALSE//,
	// CURLOPT_SSL_VERIFYPEER => TRUE,
	// CURLOPT_CAINFO => 'cacert.pem',
	));

// Execute request and get response and status code
$response = curl_exec($request);
$status = curl_getinfo($request, CURLINFO_HTTP_CODE);

// Close connection
curl_close($request);
if($status == 0 AND strpos($response, 'SUCCESS') !== 0){
	// Remove SUCCESS part (7 characters long)
	$response = substr($response, 7);

	// Urldecode it
	$response = urldecode($response);

	// Turn it into associative array
	preg_match_all('/^([^=\r\n]++)=(.*+)/m', $response, $m, PREG_PATTERN_ORDER);
	$response = array_combine($m[1], $m[2]);

	
	// Fix character encoding if needed
	if(isset($response['charset']) AND strtoupper($response['charset']) !== 'UTF-8'){
		foreach($response as $key => &$value){
			$value = mb_convert_encoding($value, 'UTF-8', $response['charset']);
		}
		$response['charset_original'] = $response['charset'];
		$response['charset'] = 'UTF-8';
	}
	// Sort on keys
	ksort($response);
	// Done!
	mysql_query("update `stshop_order` set `Status` =1 WHERE `code` ='$item_number'");
	echo "Pay Success!<br/>Go to homepage after 3 seconds!<meta http-equiv='refresh' content='3;url=../../index.php'/>";
}else{
	echo 'Pay fail';
	die();
}
?>